<?php


namespace App\Models\CacheModel\live;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class LiveUserGiftBag extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.live_user_gift_bag';

    protected $cacheModel = 'live.user_gift_bag';

    public function getUserGiftBag(int $uid)
    {
        $bagList = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage(-1)
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid)
            {
                if ($isCache)
                { // 开启了缓存
                    return $this->getInfoByIdsInData($ids, [$uid], $sortType);
                } else
                { // 没开启缓存
                    return $this->getPaginateInData([$uid], $sortType);
                }
            }, 'id', [], 0);


        $resBagList = [];
        foreach ($bagList['data'] as $bagItem)
        {
            $resBagList[$bagItem['gid']] = [
                'id' => (int)$bagItem['id'],
                'gid' => (int)$bagItem['gid'],
                'uid' => (int)$bagItem['uid'],
                'num' => (int)$bagItem['num']
            ];
        }

        return $resBagList;
    }


    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $where = ['id' => ['in', $ids]];
            } else
            {
                $where = ['uid' => $type[0]];
            }
            $data = $this
                ->where($where)
                ->column('gid,uid,num', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     *  发放用户礼物
     * @param int $uid
     * @param int $giftId
     * @param int $num
     * @return bool
     */
    public function sendUserGift(int $uid, int $giftId, int $num = 1)
    {
        try
        {
            $giftList = $this->getUserGiftBag($uid);

            if (isset($giftList[$giftId]))
            {
                $resNum = $giftList[$giftId]['num'] + $num;
                $this->where('id', $giftList[$giftId]['id'])->update(['num' => $resNum]);

                CacheManage::getInstance()->setCacheConfig($this->cacheModel,$giftList[$giftId]['id'])->setCache(['num'=>$resNum]);
            } else
            {
                $insertData = [
                    'gid' => $giftId,
                    'uid' => $uid,
                    'num' => $num,
                    'create_time' => time(),
                ];

                $id = $this->insertGetId($insertData);


                $this->listDataAdd($uid, [$id => $id]);
            }

            return true;
        }
        catch (\Exception $e)
        {
            Log::write("直播间发放用户礼物失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
            return false;
        }
    }
}
